package servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import actionForm.DeletePhoneValidationForm;

import domain.IDAOPhoneNumber;

public class DeletePhoneAction extends Action{
	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest request,
			final HttpServletResponse response) {
		if (request.getMethod().equals("POST")) {
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
			IDAOPhoneNumber dao = (IDAOPhoneNumber) context.getBean("daophonenumber");
			DeletePhoneValidationForm form =(DeletePhoneValidationForm) pForm;
			String phoneId = form.getPhoneId();
			String contactId = form.getContactId();
			boolean success = dao.deletePhoneNumber(Long.valueOf(phoneId));
			if(success){
				return new ActionRedirect(pMapping.findForward("modifyContact")).addParameter("id", contactId); 
			}	else {
				request.setAttribute("errorMessage", "The phone couldn't be deleted.");
				return pMapping.findForward("error"); 
			}
		} else if (request.getMethod().equals("GET")) {
			request.setAttribute("contactId", request.getParameter("contactId"));
			request.setAttribute("phoneId", request.getParameter("phoneId"));
			return pMapping.findForward("confirmation");
		}
		return null;
	}

}
